package app.manager;

import java.util.List; 

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import app.model.*;

public class UserManager implements UserBalancesDAO<User>{
	
	
	private String GET_All = "select u from User u";
	
	
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	@Transactional
	public int create(User user) {
		sessionFactory.getCurrentSession().save(user);
		return user.getId();
	}

	@Override
	public User read(int id) {
		User usr = (User) sessionFactory.getCurrentSession().load(User.class, id);
		return usr;
	}

	@Override
	@Transactional
	public int update(User user) {
		User usr = (User) sessionFactory.getCurrentSession().load(User.class, user.getLogin());
		if (usr != null) {
			sessionFactory.getCurrentSession().update(user);
			return usr.getId();
		}
		return -1;
	}

	@Override
	@Transactional
	public void delete(int id) {
		User usr = (User) sessionFactory.getCurrentSession().load(User.class, id);
		if (usr != null) {
			sessionFactory.getCurrentSession().delete(usr);
		}
	}

	@Override
	public List<User> getAll() {
		return sessionFactory.getCurrentSession().createQuery(GET_All).list();
	}
	
	@Transactional
	public User getUserByLogin(String login) {
		User user = (User) sessionFactory.getCurrentSession().load(User.class, login);
		if (user != null) {
			return user;
		}
		return null;
	}

}
